<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    width="1000px"
    @close="closeDialog"
  >
    <el-form ref="formRef" label-width="120px" :model="form" :rules="rules">
      <el-row :gutter="12">
        <el-col :span="12">
          <el-form-item label="规则编码" prop="barcodeRuleCode">
            <el-input v-model.trim="form.barcodeRuleCode" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则名称" prop="barcodeRuleName">
            <el-input v-model.trim="form.barcodeRuleName" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规则描述">
            <el-input
              v-model.trim="form.barcodeRuleDescribe"
              :disabled="true"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="备注">
            <el-input v-model.trim="form.remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-table
      :data="state.barcodeRuleBList"
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="级次" type="index" width="100" />
      <el-table-column label="数据源类型" prop="sourceName" width="300">
        <template #default="scope">
          <el-select
            v-model="scope.row.pkRuleSource"
            class="m-2"
            filterable
            placeholder="选择"
            @change="ruleSourceChange($event, scope.$index)"
          >
            <el-option
              v-for="rs in state.ruleSourceList"
              :key="rs.pkRuleSource"
              :label="rs.sourceName"
              :value="rs.pkRuleSource"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="格式" prop="sourceFormat" width="300">
        <template #default="scope">
          <el-input
            v-if="scope.row.sourceType == 1"
            v-model="scope.row.sourceFormat"
            disabled
          />
          <el-input
            v-if="scope.row.sourceType == 2"
            v-model="scope.row.sourceFormat"
          />
          <el-input
            v-if="scope.row.sourceType == 3"
            v-model="scope.row.sourceFormat"
          />
        </template>
      </el-table-column>
      <el-table-column label="长度" prop="formatLength" />
      <el-table-column fixed="right" label="删除" min-width="100">
        <template #default="scope">
          <el-button
            link
            size="small"
            type="primary"
            @click.prevent="deleteRow(scope.$index)"
          >
            X
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button plain type="primary" @click="addBatchRuleB()">
        <vab-icon icon="sort-desc" />
        增行
      </el-button>
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
  import { ref } from 'vue'
  import {
    addBarcodeRuleApi,
    updateBarcodeRuleApi,
    getBarcodeRuleDetailApi,
  } from '@/api/kc/barcode_rule'
  import { getRuleSourceListApi } from '@/api/kc/rule_source'
  import { localStorageConfig } from '@/config/localstorage.config'

  const pkCorp = localStorage.getItem(localStorageConfig.__pkCorp)
  const $baseMessage = inject('$baseMessage')
  const state = reactive({
    barcodeRuleBList: [],
  })

  const dialogVisible = ref(false),
    dialogTitle = ref('新增条码规则'),
    formRef = ref(),
    form = reactive({}),
    rules = reactive({
      barcodeRuleCode: [
        { required: true, trigger: 'blur', message: '请输入规则编码' },
      ],
      barcodeRuleName: [
        { required: true, trigger: 'blur', message: '请输入规则名称' },
      ],
    })

  let baseRecord = ref(null)

  const openDialog = (record) => {
    dialogVisible.value = true
    getRuleSourceList()
    if (record) {
      dialogTitle.value = '修改条码规则'
      baseRecord.value = record
      form['pkBarcodeRuleH'] = record.pkBarcodeRuleH
        ? record.pkBarcodeRuleH
        : ''
      form['barcodeRuleCode'] = record.barcodeRuleCode
        ? record.barcodeRuleCode
        : ''
      form['barcodeRuleName'] = record.barcodeRuleName
        ? record.barcodeRuleName
        : ''
      form['barcodeRuleDescribe'] = record.barcodeRuleDescribe
        ? record.barcodeRuleDescribe
        : ''
      form['remark'] = record.remark ? record.remark : ''
      getBarcodeRuleDetail()
    } else {
      dialogTitle.value = '新增条码规则'
      form['pkBarcodeRuleH'] = ''
      form['barcodeRuleCode'] = ''
      form['barcodeRuleName'] = ''
      form['barcodeRuleDescribe'] = ''
      form['remark'] = ''
      form['pkCorp'] = pkCorp
    }
  }
  const addBatchRuleB = () => {
    state.barcodeRuleBList.push({})
  }
  const deleteRow = (index) => {
    state.barcodeRuleBList.splice(index, 1)
  }

  const getBarcodeRuleDetail = async () => {
    const { code, data } = await getBarcodeRuleDetailApi({
      pkBarcodeRuleH: form.pkBarcodeRuleH,
    })
    if (code === 2000) {
      state.barcodeRuleBList = data
    }
  }
  const getRuleSourceList = async () => {
    const { code, data } = await getRuleSourceListApi({})
    if (code === 2000) {
      state.ruleSourceList = data
    }
  }
  const ruleSourceChange = (val, index) => {
    let str = ''
    const obj = state.ruleSourceList.find((item) => {
      return item.pkRuleSource === val
    })
    state.barcodeRuleBList[index].sourceType = obj.sourceType
    state.barcodeRuleBList[index].sourceName = obj.sourceName
    state.barcodeRuleBList.forEach((element) => {
      if (element.sourceType === 1) {
        element.sourceFormat = ''
      }
      if (element.sourceName) {
        str = str + element.sourceName + ','
      } else {
        str = str + ' ' + ','
      }
    })
    form.barcodeRuleDescribe = str
  }
  const save = () => {
    form.kcBarcodeRuleBs = state.barcodeRuleBList
    if (!formRef.value) return
    formRef.value.validate(async (valid) => {
      if (valid) {
        let res = null
        if (baseRecord.value) {
          res = await updateBarcodeRuleApi({
            ...form,
          })
        } else {
          res = await addBarcodeRuleApi({
            ...form,
          })
        }
        if (res && res.code === 2000) {
          $baseMessage(res.msg, 'success')
          _emit('success-callback')
          closeDialog()
        } else {
          $baseMessage(res && res.msg ? res.msg : '操作失败,请重试', 'error')
        }
      } else {
        return false
      }
    })
  }
  const closeDialog = () => {
    baseRecord.value = null
    dialogVisible.value = false
  }
  defineExpose({ openDialog })
  const _emit = defineEmits(['success-callback'])
</script>
